package store.aixx.security.ch4.security.auth.ldap;

import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author yukai
 * @since 2021年12月10日 15:52
 */
@RequiredArgsConstructor
public class LdapMultiAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    private final LdapUserRepo ldapUserRepo;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        // 忽略认证检查
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

        return ldapUserRepo.findByUsernameAndPassword(username, authentication.getCredentials().toString()).orElseThrow(() -> new BadCredentialsException("用户名或密码错误!"));
    }
}
